//
//  PullRefreshTableController.m
//  TianyaBlog
//
//  Created by jiaoqiang on 10-10-16.
//  Copyright __MyCompanyName__ 2010. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "PullRefreshTableController.h"
#import "NSDate+Custom.h"
#import "UIImageView+Custom.h"
#import "Instance.h"

#define REFRESH_HEADER_HEIGHT 48.0f
#define REFRESH_HEADER_MAX_HEIGHT 48.0f

@interface PullRefreshTableController(Private)
- (void)addPullToRefreshHeader;
- (void)stopLoading;
- (void)beginDragging;
- (UIImage*)getBackgroundViewImage:(CGRect)rect;
@end

@implementation PullRefreshTableController

@synthesize pullTableView=pullTableView_;
@synthesize textPull=textPull_;
@synthesize textRelease=textRelease_;
@synthesize textLoading=textLoading_;
@synthesize textLastTime=textLastTime_;

- (id)init
{
	if (self = [super init]) 
    {
		self.textPull = @"下拉可以刷新";
        self.textRelease = @"松手即可更新";
        self.textLoading = @"更新中";
	}
	return self;
}

- (void)viewDidLoad 
{
    [super viewDidLoad];
    [self addPullToRefreshHeader];
}

- (void)addPullToRefreshHeader 
{
    refreshHeaderView_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0 - REFRESH_HEADER_MAX_HEIGHT, 320, REFRESH_HEADER_MAX_HEIGHT)];
    refreshHeaderView_.backgroundColor = [UIColor clearColor];
    
    refreshLabel_ = [[UILabel alloc] initWithFrame:CGRectMake(50, REFRESH_HEADER_MAX_HEIGHT-REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
    refreshLabel_.backgroundColor = [UIColor clearColor];
	refreshLabel_.textColor = [UIColor blackColor];
    refreshLabel_.text = self.textPull;
    refreshLabel_.font = [UIFont boldSystemFontOfSize:13.0];
    refreshLabel_.numberOfLines = 2;
    refreshLabel_.textAlignment = UITextAlignmentLeft;

    refreshArrow_ = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refresh_up.png"]];
    refreshArrow_.frame = CGRectMake((REFRESH_HEADER_HEIGHT - 20) / 2,
                                    (REFRESH_HEADER_HEIGHT - 20) / 2,
                                    20, 20);
    
    refreshSpinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    refreshSpinner_.frame = CGRectMake((REFRESH_HEADER_HEIGHT - 20) / 2, (REFRESH_HEADER_HEIGHT - 20) / 2, 20, 20);
    refreshSpinner_.hidesWhenStopped = YES;
    
    [refreshHeaderView_ addSubview:refreshLabel_];
    [refreshHeaderView_ addSubview:refreshArrow_];
    [refreshHeaderView_ addSubview:refreshSpinner_];
    
    headBackgroundView_ = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 0)];
    headBackgroundView_.hidden=TRUE;
    [self.pullTableView addSubview:headBackgroundView_];
    [self.pullTableView sendSubviewToBack:headBackgroundView_];
    [headBackgroundView_ release];
    
    [self.pullTableView addSubview:refreshHeaderView_];
}

- (void)showMore 
{
	isRefresh_ = FALSE;
}

- (void)beginDragging 
{
	
}

- (void)changeBackgroundViewFrame
{
//    if (headBackgroundView_) 
//    {
//        CGRect rect=headBackgroundView_.frame;
//        rect.origin.y=pullTableView_.contentOffset.y;
//        rect.size.height=-pullTableView_.contentOffset.y;
//        headBackgroundView_.frame=rect;
//        headBackgroundView_.image=[self getBackgroundViewImage:rect];
//        headBackgroundView_.hidden=FALSE;
//    }
}

- (UIImage*)getBackgroundViewImage:(CGRect)rect
{
    if (rect.size.height==0)
    {
        return nil;
    }
    else
    {
        UIImage* backImage=[UIImage imageNamed:@"slide_bg.png"];
        rect.origin.y=0;
        return [backImage getSubImage:rect];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView 
{
	[self beginDragging];
    if (isLoading_)
        return;
    isDragging_ = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
    if (isLoading_) 
    {
        // Update the content inset, good for section headers
        if (scrollView.contentOffset.y > 0)
        {
            self.pullTableView.contentInset = UIEdgeInsetsZero;
            headBackgroundView_.hidden=TRUE;
        }
        else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT)
        {
            self.pullTableView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            [self changeBackgroundViewFrame];
        }
        
    } 
    else if (isDragging_) 
    {
		if (self.textLastTime == nil) {
			self.textLastTime = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
		}
        // Update the arrow direction and label
        [UIView beginAnimations:nil context:NULL];
        if (scrollView.contentOffset.y < -REFRESH_HEADER_HEIGHT) {
            // User is scrolling above the header
			refreshLabel_.text = [NSString stringWithFormat:@"%@\n最后更新的时间：%@", self.textRelease, [[NSDate dateWithTimestamp:self.textLastTime] intervalSinceNow]];
            [refreshArrow_ layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
        } else { // User is scrolling somewhere within the header
            refreshLabel_.text = [NSString stringWithFormat:@"%@\n最后更新的时间：%@", self.textPull, [[NSDate dateWithTimestamp:self.textLastTime] intervalSinceNow]];
			refreshLabel_.font = [UIFont systemFontOfSize:13];
            [refreshArrow_ layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
        }
        [UIView commitAnimations];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate 
{
    if (isLoading_) 
        return;
    isDragging_ = NO;
    if (scrollView.contentOffset.y <= -REFRESH_HEADER_HEIGHT) 
    {
        // Released above the header
        [self startLoading];
    }
}

- (void)startLoading 
{
    // Show the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];
    self.pullTableView.contentInset = UIEdgeInsetsMake(REFRESH_HEADER_HEIGHT, 0, 0, 0);
    refreshLabel_.text = self.textLoading;
    refreshArrow_.hidden = YES;
    [refreshSpinner_ startAnimating];
    [UIView commitAnimations];
    
    // Refresh action!
    [self refresh];
	isLoading_ = YES;
}

- (void)stopLoading 
{
    isLoading_ = NO;
    // Hide the header
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationDidStopSelector:@selector(stopLoadingComplete:finished:context:)];
    self.pullTableView.contentInset = UIEdgeInsetsZero;
    [refreshArrow_ layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
    [UIView commitAnimations];
    //[refreshArrow_ stopRotating];
	self.textLastTime = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
}

- (void)stopLoadingComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context 
{
    // Reset the header
    refreshLabel_.text = self.textPull;
    refreshArrow_.hidden = NO;
    [refreshSpinner_ stopAnimating];
}

- (void)refresh 
{
    // This is just a demo. Override this method with your custom reload action.
    // Don't forget to call stopLoading at the end.
	isRefresh_ = TRUE;
    [self performSelector:@selector(stopLoading) withObject:nil afterDelay:1.0];
}

- (void)viewDidUnload 
{
    [refreshHeaderView_ release];
    refreshHeaderView_=nil;
    [refreshLabel_ release];
    refreshLabel_=nil;
    [refreshArrow_ release];
    refreshArrow_=nil;
    [refreshSpinner_ release];
    refreshSpinner_=nil;
    [super viewDidUnload];
}

- (void)dealloc 
{
    [refreshHeaderView_ release];
    [refreshLabel_ release];
    [refreshArrow_ release];
    [refreshSpinner_ release];
    [pullTableView_ release];
    [textPull_ release];
    [textRelease_ release];
    [textLoading_ release];
    [super dealloc];
}

@end
